package com.zyk.scaffold.user.mail.sender;

import com.alibaba.fastjson.JSON;
import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.common.utils.StringUtils;
import com.zyk.scaffold.user.mail.properties.LocalMailProperties;
import com.zyk.scaffold.user.mail.properties.MailServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
public class LocalMailServerSender implements ILocalMailSender {

    private JavaMailSenderImpl javaMailSender;
    private LocalMailProperties localMailProperties;
    private String name;

    public LocalMailServerSender(JavaMailSenderImpl javaMailSender, String name, LocalMailProperties localMailProperties) {
        this.javaMailSender = javaMailSender;
        this.localMailProperties = localMailProperties;
        this.name = name;
    }

    @Override
    public boolean send(SenderMessage senderMessage) {
        if (!valid(senderMessage)) {
            log.error("邮件发送,参数校验不通过：{}", JSON.toJSONString(senderMessage));
            AssertUtil.error("邮件发送,参数校验不通过");
        }
        // 密码刷新生效
        if (localMailProperties.getRefreshPassword()) {
            resetPassword();
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(senderMessage.getFrom());
            helper.setTo(senderMessage.getTo());
            helper.setSubject(senderMessage.getSubject());
            helper.setText(senderMessage.getContent(), true);
            javaMailSender.send(message);
            return true;
        } catch (MessagingException e) {
            log.error("邮件发送失败,参数：" + JSON.toJSONString(senderMessage), e);
            AssertUtil.error("邮件发送失败");
        } catch (Exception e) {
            log.error("邮件发送出现异常,参数：" + JSON.toJSONString(senderMessage), e);
            AssertUtil.error("邮件发送出现异常");
        }
        return false;
    }

    private void resetPassword() {
        for (MailServer mailServer : localMailProperties.getMailServers()) {
            String name = mailServer.getName();
            if (StringUtils.equals(this.name, name)) {
                this.javaMailSender.setPassword(mailServer.getMailConfig().getPassword());
                return;
            }
        }
    }

}
